<template>
  <div class="background-container">
    <!-- 后台点单控制台 -->
    <el-card class="box-card">
      <!-- 查询输入框 -->
      <div slot="header">
        <el-form size="mini" class="demo-form-inline">
          <el-row>
            <el-col :span="5" :offset="1">
              <el-form-item>
                <el-input size="small" v-model="name" placeholder="输入名字，解锁奶茶"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2" :offset="1">
              <el-form-item>
                <el-button type="primary" @click="GetGoodsData">一键召唤奶茶</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 商品列表 -->
      <el-row :gutter="20">
        <el-col :span="6" v-for="(item, index) in goods" :key="index" style="margin-bottom: 20px;">
          <el-card class="goods-card" shadow="hover">
            <el-avatar shape="square" :size="150" :src="image + item.Images" fit="cover"></el-avatar>
            <div class="goods-info">
              <div class="goods-title">{{ item.Name }}</div>
              <div class="goods-price">{{ item.Price }} 元</div>
            </div>
            <div>
              <el-button v-if="!item.Use_Property" type="text" @click="addToCart(item)">+🥤 点它！</el-button>
              <el-button v-else type="text" @click="ShowProperty(item)">+ 选择规格</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 购物车 -->
    <el-card class="card">

      <!-- 头部 -->
      <div slot="header">
        <span class="cart-title">🛒 购物车</span>
        <span class="cart-total" style="margin-left: 20px;">共 {{ cart.length }} 件商品，总计 {{ cart.reduce((acc, cur) => acc + cur.TotalAmount, 0)  }} 元</span>
        <!-- 清空所有 -->
        <el-button type="text" @click="cart=[]" style="margin-left: 20px; border: 2px solid #eee; padding: 5px;">🗑️清空购物车</el-button>
      </div>

      <!-- 列表 -->
      <div v-if="cart.length > 0">
        <div v-for="(item, index) in cart" :key="index" class="cart-item"  >
            <!-- 商品图片 -->
          <el-avatar shape="square" :size="80"  :src="image + item.Images"  style="border: 2px solid #eee; margin: 10px;"></el-avatar>
          
          <!-- 商品单价 -->
          <span style="font-size: 12px;display: inline-block;width: 300px;" >
            名称：{{ item.Name }} - 单价： {{ item.Price }}
            -总价：
            <span style="color: red; font-size: 15px;">{{item.TotalAmount}}$</span>
          </span>
          

          <!-- 商品数量 -->
           <el-input-number v-model="item.OrderNumber" :min="1" :max="100" style="margin-left: 10px;" @change="updateCart()"></el-input-number>

           <!-- 商品删除按钮 -->
          <el-button type="text" @click="cart.splice(index, 1)" style="margin-left: 50px; border: 2px solid #eee; padding: 5px;">-🥤删它！</el-button>
        </div>
      </div>
      <div v-else class="empty-cart">
        🚫 购物车空空如也，快来加点奶茶吧！
      </div>

      <!-- 结算按钮 -->
      <div style="text-align: right; margin-top: 20px;">
          <el-button @click="Settlement()">立即结算</el-button>
      </div>
    </el-card>

    <!-- 弹窗框 商品规格-->
      <el-dialog title="选择规格" :visible.sync="dialogVisible" width="25%" :before-close="handleClose">  
        <Spec v-model="dialogVisible"  :data="cart" @update:data="addToCarts" @Close="handleClose"></Spec>
      </el-dialog>
  </div>
</template>

<script>
import Spec from  '../Console/GoodsSpec.vue'
import bases from '../../plugins/base.js'
export default {
  data() {
    return {
      page: 1,  //当前页
      size: 8,  //每页显示条数
      name: '', //商品名称
      total: 0,  //总数
      goods: [], //商品数据
      cart: [], //购物车
      image: '' ,//图片路径
      dialogVisible: false //弹窗框是否显示
    }
  },
  methods: {
    //添加带有规格的商品
    addToCarts(value){
      if(this.cart.some(x => x.Gid == value.Gid)){
        console.log("购物车存在");
            this.cart.find(x => x.Gid == value.Gid).OrderNumber++;//存在就数量加1     
            this.updateCart();//更新购物车商品总价 
      }else
          this.cart.push(value);
    },
    //获取商品数据
    GetGoodsData() {
      this.axios(
        {
          method: 'get',
          url: 'Goods/Page',
          params: {
            page: this.page,
            size: this.size,
            name: this.name
          }
        }
      ).then(response => {
        console.log(response);
        console.log('response.data.data: ', response.data.data);
        console.log('response.count: ', response.data.count);
        this.goods = response.data.data;
        this.total = response.data.count;

      }).catch(error => {
        console.log('error: ', error);
        this.$message.error('获取奶茶数据失败，快来检查一下吧！');
      })
    },
    //加入购物车
    addToCart(item) {
      console.log('GID: ', item.Id);
      // 判断商品存在购物车吗
      console.log(this.cart);
      if(this.cart.some(x => x.Gid == item.GID)){
        console.log("购物车存在");
            this.cart.find(x => x.Gid == item.GID).OrderNumber++;//存在就数量加1     
            this.updateCart();//更新购物车商品总价 
      }else{
        console.log("购物车不存在");
        //组装默认订单数据
      this.cart.push({
          UserId:sessionStorage.getItem('UserId').toString(),
          Gid:item.GID,
          CreateDate:'',
          OrderStatus:'待制作',
          TotalAmount:item.Price,
          OrderNumber:1,
          Price:item.Price,
          Name:item.Name,
          Images:item.Images,
          Notes:'',
          OrdersSpec:[
            // 单选没有属性规格
          ]
      });

      this.$message.success(`🥤 ${item.Name} 已加入购物车，快来喝它！`);
    }
    },
    // 更新购物车商品总价
    updateCart() {
        this.cart.forEach(x => {
          x.TotalAmount = x.Price * x.OrderNumber;
        });
    },
    //结算
    Settlement(){
      if(this.cart.length == 0){
            this.$message.error('购物车为空，快来点点奶茶吧！');
      }else{
            // 跳转到结算页面
            //添加数据到vuex
            this.$store.commit('setCart', this.cart);
            console.log(this.cart);
            this.$router.push({ path: '/settlement' });
      }
    },
    //显示规格
    ShowProperty(item){
        console.log(item.GoodPropertyKey);
        this.$store.commit('setMilkTea', item);  //赋值商品信息
        this.dialogVisible = true;  //弹窗显示
    },
    //关闭弹窗
    handleClose(){
      this.dialogVisible = false;
    }
  },
    created() {
    //创建之后执行
    this.image = bases.imgUrl;

    //获取商品数据  
    this.GetGoodsData();
  },
  // 注册组件
  components: {
    Spec
  }

}
</script>

<style scoped>
/* 全局字体 */
body {
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

.background-container {
  position: relative;
  background-image: url('./img/beijing.jpg'); /* 替换为你的图片路径 */
  background-size: cover; /* 背景图片覆盖整个容器 */
  background-position: center; /* 背景图片居中 */
  background-repeat: no-repeat; /* 不重复背景图片 */
  opacity: 1; /* 设置背景图片的透明度 */
}

.box-card {
  position: relative;
  z-index: 1; /* 确保内容在背景之上 */
  opacity: 0.8; /* 设置背景图片的透明度 */
  padding: 20px; /* 内边距 */
}

.card {
  position: relative;
  z-index: 1; /* 确保内容在背景之上 */
  opacity: 0.8; /* 设置背景图片的透明度 */
}

.goods-card {
  transition: transform 0.3s ease;
}

.goods-card:hover {
  transform: translateY(-5px);
}


.goods-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.goods-price {
  font-size: 14px;
  color: #ff4949;
  margin-top: 5px;
}

.add-button {
  font-size: 14px;
  color: #409eff;
  font-weight: 500;
}

.cart-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.cart-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
  color: #666;
}

.empty-cart {
  font-size: 14px;
  color: #999;
  text-align: center;
}
</style>